package HTMLTemplateProTemplate;
use strict;

use HTML::Template::Pro;
use File::Spec;

sub new
{
	my $class = shift;
	
	return bless {
		tmpl => new HTML::Template::Pro(
			filename => '',
			loop_context_vars	=> 3,
			global_vars	=> 1,
		),
		cache => {},
	}, $class;
}

sub set_path
{
	my ($self, $path) = @_;
	
	$self->{tmpl}->{path} = $path;	
}

sub get
{
	my ($self, $tmplname) = @_;
	
	return undef unless $self->_find_template($tmplname);

	$self->{tmpl}->{filename} = $tmplname;
	
	return $self;
}

sub _find_template
{
	my ($self, $tmplname) = @_;

	return $self->{cache}{$tmplname} if defined $self->{cache}{$tmplname};
	
	for my $dir ( @{$self->{tmpl}->{path}} ){
		my $fname = File::Spec->catfile($dir, $tmplname);
		if (-e $fname){
			$self->{cache}{$tmplname} = $fname;
			return $fname;
		}
	}
	return undef;
}

sub render
{
	my ($self, $context) = @_;
	
	$self->{tmpl}->clear_params();
	$self->{tmpl}->param( ( $context->{dict} ) ) if $context->{dict};
	
	return $self->{tmpl}->output;	
}
1;